﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Wise.TimeWarrior.DTO;
using Wise.TimeWarrior.Interfaces;
using Wise.TimeWarrior.Helpers;

namespace Wise.TimeWarrior.Impl
{
    /// <summary>
    /// <see cref="IDataStore"/>
    /// </summary>
    public class DataStoreService : IDataStore
    {
        private string DATA_STORE_FILENAME = @"store.ser";

        /// <summary>
        /// <see cref="IDataStore.DataStorePath"/>
        /// </summary>
        public string DataStorePath { set; private get; }

        private String FullStorePath
        {

            get
            {
                lock (this) { return Path.Combine(DataStorePath, DATA_STORE_FILENAME); }
            }
        }

        /// <summary>
        /// <see cref="IDataStore.SaveData"/>
        /// </summary>
        public void SaveData(List<UserEventDto> data)
        {
            lock (this)
            {
                PrepareAndCheckDirectories();
                List<UserEventDto> currentData = null;

                currentData = File.Exists(FullStorePath)
                    ? SerializationHelper.Deserialize<List<UserEventDto>>(FullStorePath)
                    : new List<UserEventDto>();

                currentData.AddRange(data);
                SerializationHelper.Serialize<List<UserEventDto>>(FullStorePath, currentData);
            }
        }


        /// <summary>
        /// <see cref="IDataStore.GetData"/>
        /// </summary>
        public List<UserEventDto> GetData(DateTime from, DateTime? to)
        {
            lock (this)
            {
                PrepareAndCheckDirectories();
                if (File.Exists(FullStorePath))
                {
                    List<UserEventDto> currentData = SerializationHelper.Deserialize<List<UserEventDto>>(FullStorePath);

                    return (to.HasValue)
                        ? currentData.Where(p => p.EventDate >= DateTimeHelper.LowerToDayStart(from) && p.EventDate < DateTimeHelper.UpperToDayEnd(to.Value)).ToList()
                        : currentData.Where(p => p.EventDate >= DateTimeHelper.LowerToDayStart(from)).ToList();
                }
                else
                {
                    return new List<UserEventDto>();
                }
            }
        }


        private bool PrepareAndCheckDirectories()
        {
            lock (this)
            {
                if (!Directory.Exists(DataStorePath))
                {
                    Directory.CreateDirectory(DataStorePath);
                }
                return File.Exists(DataStorePath);
            }
        }
    }
}
